package com.example.units;

import java.io.FileWriter;
import java.sql.*;
import java.util.*;

public class CodeGenerator {
    // ================== 配置区(修改此处即可) ==================
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/remberCount?"
            + "useSSL=false"
            + "&allowPublicKeyRetrieval=true"
            + "&serverTimezone=Asia/Shanghai"
            + "&characterEncoding=UTF-8"
            + "&nullCatalogMeansCurrent=true";  // 关键修复参数[1,6](@ref)
    private static final String USERNAME = "root";
    private static final String PASSWORD = "12345678";

    // 包路径配置
    private static final String BASE_PACKAGE = "com.example";
    private static final String ENTITY_PACKAGE = "entity";
    private static final String MAPPER_PACKAGE = "mapper";
    private static final String SERVICE_PACKAGE = "service";
    private static final String CONTROLLER_PACKAGE = "controller";

    // 表名配置
    private static final String TABLE_NAME = "log";  // 确认业务表存在
    private static final String CLASS_PREFIX = "";
    private static final String CLASS_SUFFIX = "";

    // ================== 类型映射增强 ==================
    private static final Map<String, String> TYPE_MAPPING = new HashMap<>() {{
        put("varchar", "String");
        put("char", "String");
        put("text", "String");
        put("int", "Integer");
        put("bigint", "Long");
        put("datetime", "LocalDateTime");  // 使用Java8时间类型[3](@ref)
        put("timestamp", "LocalDateTime");
        put("date", "LocalDate");
        put("decimal", "BigDecimal");
        put("tinyint", "Integer");
        put("bit", "Boolean");
    }};

    public static void main(String[] args) throws Exception {
        Class.forName(DRIVER);
        try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
            DatabaseMetaData metaData = conn.getMetaData();

            // 验证表存在性[1](@ref)
            try (ResultSet tables = metaData.getTables(null, null, TABLE_NAME, null)) {
                if (!tables.next()) {
                    throw new SQLException("表" + TABLE_NAME + "不存在");
                }
            }

            generateEntity(metaData);
            generateMapper();
            generateService();
            generateController();
        }
    }

    private static void generateEntity(DatabaseMetaData metaData) throws Exception {
        String className = convertToClassName(TABLE_NAME);
        StringBuilder code = new StringBuilder()
                .append("package ").append(BASE_PACKAGE).append(".").append(ENTITY_PACKAGE).append(";\n\n")
                .append("import lombok.Data;\n")
                .append("import java.time.LocalDateTime;\n")
                .append("import java.time.LocalDate;\n")
                .append("import java.math.BigDecimal;\n\n")
                .append("@Data\n")
                .append("public class ").append(className).append(" {\n");

        try (ResultSet columns = metaData.getColumns(null, null, TABLE_NAME, null)) {
            while (columns.next()) {
                String colName = columns.getString("COLUMN_NAME");
                String typeName = columns.getString("TYPE_NAME").toLowerCase();
                String colType = TYPE_MAPPING.getOrDefault(typeName, "Object");

                code.append("    private ").append(colType).append(" ")
                        .append(convertToFieldName(colName)).append(";\n");
            }
        }
        code.append("}");
        writeToFile(ENTITY_PACKAGE, className + ".java", code.toString());
    }

    // ================== 增强Mapper生成 ==================11
    private static void generateMapper() {
        String className = convertToClassName(TABLE_NAME);
        String mapperContent = String.format(
                "package %s.%s;\n\n"
                        + "import org.apache.ibatis.annotations.*;\n"
                        + "import java.util.List;\n\n"
                        + "@Mapper\n"
                        + "public interface %sMapper extends BaseMapper<%s> {\n"

                        + "}",
                BASE_PACKAGE, MAPPER_PACKAGE,
                className, className, className,
                TABLE_NAME, className,
                TABLE_NAME, className);

        writeToFile(MAPPER_PACKAGE, className + "Mapper.java", mapperContent);
    }

    // ================== 增强Service生成 ==================
    private static void generateService() {
        String className = convertToClassName(TABLE_NAME);
        String serviceContent = String.format(
                "package %s.%s;\n\n"
                        + "import org.springframework.stereotype.Service;\n"
                        + "import org.springframework.beans.factory.annotation.Autowired;\n"
                        + "import %s.%s.%sMapper;\n"
                        + "import java.util.List;\n\n"
                        + "@Service\n"
                        + "public class %sService {\n\n"
                        + "    @Autowired\n"
                        + "    private %sMapper mapper;\n\n"

                        + "}",
                BASE_PACKAGE, SERVICE_PACKAGE,
                BASE_PACKAGE, MAPPER_PACKAGE, className,
                className, className, className, className, className);

        writeToFile(SERVICE_PACKAGE, className + "Service.java", serviceContent);
    }

    // ================== 增强Controller生成 ==================
    private static void generateController() {
        String className = convertToClassName(TABLE_NAME);
        String controllerContent = String.format(
                "package %s.%s;\n\n"
                        + "import org.springframework.web.bind.annotation.*;\n"
                        + "import %s.%s.%sService;\n"
                        + "import java.util.List;\n\n"
                        + "@RestController\n"
                        + "@RequestMapping(\"/api/%s\")\n"
                        + "public class %sController {\n\n"

                        + "}",
                BASE_PACKAGE, CONTROLLER_PACKAGE,
                BASE_PACKAGE, SERVICE_PACKAGE, className,
                className.toLowerCase(), className,
                className, className, className,
                className, className, className);

        writeToFile(CONTROLLER_PACKAGE, className + "Controller.java", controllerContent);
    }

    // ================== 工具方法 ==================
    private static String convertToClassName(String tableName) {
        String name = tableName.replace(CLASS_PREFIX, "")
                .replaceAll("_", " ");
        return Arrays.stream(name.split(" "))
                .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1))
                .reduce("", String::concat) + CLASS_SUFFIX;
    }

    private static String convertToFieldName(String columnName) {
        String[] parts = columnName.split("_");
        return parts[0].toLowerCase() + Arrays.stream(parts)
                .skip(1)
                .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase())
                .reduce("", String::concat);
    }

    private static void writeToFile(String packageName, String fileName, String content) {
        try {
            String path = System.getProperty("user.dir") + "/remberCountJava/src/main/java/" +
                    BASE_PACKAGE.replace(".", "/") + "/" + packageName.replace(".", "/");
            new java.io.File(path).mkdirs();

            try (FileWriter writer = new FileWriter(path + "/" + fileName)) {
                writer.write(content);
                System.out.println("生成成功: " + fileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}